package com.ztstkj.lzscale.fragments

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.proembed.service.MyService
import com.sscl.baselibrary.utils.DebugUtil
import com.ztstkj.lzscale.R
import com.ztstkj.lzscale.ui.SettingActivity
import com.ztstkj.lzservices.exceptions.LogConstant
import com.ztstkj.lzservices.exceptions.apiCall
import com.ztstkj.lzservices.extension.ViewExtension.setOnClickListenerAfterMultipleClicks
import com.ztstkj.lzservices.mmkvs.MmkvManager
import com.ztstkj.lzservices.networks.DowloadManager
import com.ztstkj.lzservices.networks.NetworkUtils
import com.ztstkj.lzservices.retrofits.Api
import com.ztstkj.lzservices.utils.SpeakUtil
import com.ztstkj.lzservices.utils.UrlUtil
import kotlinx.coroutines.launch
import java.io.File

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [NavFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class NavFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private lateinit var tvDownload: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_nav, container, false)
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        //*************2秒内点击顶部导航3次，跳转到设置页面
        var fragImageNav = view.findViewById<ImageView>(R.id.imgNav)
        fragImageNav.setOnClickListenerAfterMultipleClicks {
            DebugUtil.debugOut("跳转到设置页面")
            startActivity(Intent(context, SettingActivity::class.java))
        }
        var fragmentRealNo = view.findViewById<TextView>(R.id.tvEquipmentRealNo)
        fragmentRealNo.text = "设备号：${DeviceUtils.getAndroidID().uppercase()}"
        fragmentRealNo.setOnClickListenerAfterMultipleClicks{
            var mXService = MyService(context)
            mXService.hideNavBar = !mXService.hideNavBar

        }
        tvDownload=view.findViewById<TextView>(R.id.tvDownload)

        var fragmentVersion = view.findViewById<TextView>(R.id.tvVersion)
        fragmentVersion.text = "V ${AppUtils.getAppVersionName()}"
        fragmentVersion.setOnClickListener {
            if(NetworkUtils.onLine){
                lifecycleScope.launch {
                    val resp = apiCall { Api.get().getLatestApk(DeviceUtils.getAndroidID(),4) }
                    val apk = resp.data
                    if (resp.success && apk != null&&apk.id>0) {
                        if (apk.apkVersion.toInt() > AppUtils.getAppVersionCode()) {
                            context?.let { it1 -> SpeakUtil.speech(it1,"检测到新版本，开始下载") }
                            downloadApp(apk.downloadUrl)
                        }else{
                            context?.let { it1 -> SpeakUtil.speech(it1,"当前是最新版本") }
                        }
                    } else {
                        context?.let { it1 -> SpeakUtil.speech(it1,"未检测到最新版本") }
                    }
                }
            }else{
                context?.let { it1 -> SpeakUtil.speech(it1,"当前没有网络") }
            }

        }


    }
    @SuppressLint("SetTextI18n")
    private fun downloadApp(url: String) {
        if (url.isEmpty()) return
        MmkvManager.addLog(LogConstant.APPDOWN, "开始下载")
        val filePath = "${context?.externalCacheDir!!.absolutePath}/${UrlUtil.getUriFileName(url)}"
        if (File(filePath).exists()) {
            MmkvManager.addLog(LogConstant.APPDOWN, "本地有文件，开始安装，path=${filePath}")
            tvDownload.text="即将重启"
            installApkXc(filePath)
        } else {
            MmkvManager.addLog(LogConstant.APPDOWN, "本地没有文件，开始下载，path=${filePath}")
            lifecycleScope.launch {
                var processNum = 0
                DowloadManager.download(url, filePath, onProcess = { _, _, process ->
                    val processInt = (process * 100).toInt()
                    if (processInt % 10 == 0 && processNum != processInt) {
                        processNum = processInt
                        tvDownload.text="下载$processInt%"
                        MmkvManager.addLog(LogConstant.APPDOWN, "process =$processInt%")
                    }
                }, onSuccess = {
                    MmkvManager.addLog(LogConstant.APPDOWN, "下载成功,地址：$filePath")
                    tvDownload.text="即将重启"
                    installApkXc(filePath)
                }, onError = {
                    it.printStackTrace()
                    MmkvManager.addLog(LogConstant.APPDOWN, "下载失败,${it.message}")
                })
            }
        }
    }
    private fun installApkXc(filePath: String) {
        DebugUtil.warnOut("安装：installApkXc")
        var mXService = MyService(context)
        mXService.silentInstallApk(filePath, AppUtils.getAppPackageName(), true)
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment NavFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            NavFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}